package com.cloudpivot.receivales.ding.scenegroup.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.ding.basic.domain.InteractiveCardForCPDTO;
import com.cloudpivot.receivales.ding.basic.service.impl.HttpAPIServiceForDing;
import com.cloudpivot.receivales.ding.scenegroup.domain.*;
import com.cloudpivot.receivales.ding.scenegroup.service.ScenegroupService;
import com.cloudpivot.receivales.ding.basic.service.DingBasicService;
import com.cloudpivot.receivales.ding.basic.domain.ScenegroupForCPDTO;
import com.cloudpivot.receivales.ding.basic.service.impl.CPServiceImpl;
import com.cloudpivot.receivales.ding.util.DingUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 钉钉场景群服务
 */
@Service
@Slf4j
public class ScenegroupServiceImpl implements ScenegroupService {

    @Autowired
    private DingBasicService dingBasicService;
    @Autowired
    private HttpAPIServiceForDing httpAPIServiceForDing;
    @Autowired
    private CPServiceImpl cpService;
    @Value("${dingcallback.appsecret}")
    private String APPSECRET;
    @Value("${dingcallback.appkey}")
    private String APPKEY;
    @Value("${myprops.maycururl}")
    private String MAYCURURL;

    /**
     * 新建场景群 ，通过crm
     * @param scenegroupDTO
     * @return
     */
    @Override
    public RspDTO createScenegroupByCrm(ScenegroupDTO scenegroupDTO) {
        try {
            //转化下对象内容
            //群主 需要接受转换
            String groupMainid="";
            JSONObject mainId = new JSONObject();
            mainId.put("ids", scenegroupDTO.getOwner_user_id());
            String covmainidUrl=String.format("%s","http://172.17.100.14:8989/systemBase/getDingUserByCrmId");
            String ret=httpAPIServiceForDing.doPost(covmainidUrl, mainId.toJSONString(), null);
            JSONObject mainidRet = JSONObject.parseObject(ret);
            if (mainidRet.getInteger("code") == 1) {
                groupMainid = mainidRet.getString("msg");
            }else{
                return new RspDTO(-100);
            }
            //群员
            String groupuser="";
            JSONObject greoupId = new JSONObject();
            mainId.put("ids", scenegroupDTO.getUser_ids());
            String userRet=httpAPIServiceForDing.doPost(covmainidUrl, mainId.toJSONString(), null);
            JSONObject usersRet = JSONObject.parseObject(userRet);
            if (usersRet.getInteger("code") == 1) {
                groupuser = usersRet.getString("msg");
            }else{
                return new RspDTO(-100);
            }
            //对象更新
            scenegroupDTO.setOwner_user_id(groupMainid);
            scenegroupDTO.setUser_ids(groupuser);
            log.info("待新建场景群对象，{}", JSONObject.toJSONString(scenegroupDTO));
            String retOpenId=createScenegroup(scenegroupDTO);
            if(StringUtils.isNotBlank(retOpenId)){
                Map<String, Object> map = new HashMap<>();
                map.put("openConverstaionId", retOpenId);
                return new RspDTO(1,  map);
            }else{
                return new RspDTO(-99);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new RspDTO(-10000);
        }

    }

    /**
     * 新建群，但是不能通过api 修改群内人员的角色
     * @param scenegroup
     * @return
     */
    @Override
    public String createScenegroup(ScenegroupDTO scenegroup) {
        String access_token=dingBasicService.getToken("dinggroup");
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/im/chat/scenegroup/create");
        OapiImChatScenegroupCreateRequest req = new OapiImChatScenegroupCreateRequest();
        req.setOwnerUserId(scenegroup.getOwner_user_id());
        req.setUserIds(scenegroup.getUser_ids());
        req.setIcon(scenegroup.getIcon());
        req.setMentionAllAuthority(scenegroup.getMention_all_authority());
        req.setShowHistoryType(scenegroup.getShow_history_type());
        req.setValidationType(scenegroup.getValidation_type());
        req.setSearchable(scenegroup.getSearchable());
        req.setChatBannedType(scenegroup.getChat_banned_type());
        req.setManagementType(scenegroup.getManagement_type());
        req.setTitle(scenegroup.getTitle());
        req.setTemplateId(scenegroup.getTemplate_id());

        try {
            OapiImChatScenegroupCreateResponse rsp = client.execute(req, access_token);
            log.info("场景群创建：{}", JSONObject.toJSONString(rsp));
            if(rsp.getSuccess()){
                //创建成功
                String openConverstaionId=rsp.getResult().getOpenConversationId();
                String chatId=rsp.getResult().getChatId();
                //写入CP接口
                ScenegroupForCPDTO req1 = new ScenegroupForCPDTO();
                req1.setChangjingqmc(scenegroup.getTitle());
                req1.setChatId(chatId);
                req1.setUserids(scenegroup.getUser_ids());
                req1.setOpenConversationId(openConverstaionId);
                req1.setManUser(scenegroup.getOwner_user_id());
                String rsp1 = cpService.addScenegroupInfoToCP(req1);
                if (StringUtils.isBlank(rsp1)) {
                    log.info("新增到 CP场景群记录 出错。（钉钉场景群已经创建）openid:{}", openConverstaionId);
                    return null;
                }
                return openConverstaionId;
            }
        } catch (ApiException e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    @Override
    public String addUserToScenegroup(AddUserToScenegroupDTO entity) {
        String access_token = dingBasicService.getToken("dinggroup");
        DingTalkClient client=new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/im/chat/scenegroup/member/add");
        OapiImChatScenegroupMemberAddRequest req = new OapiImChatScenegroupMemberAddRequest();
        req.setOpenConversationId(entity.getScenegroupId());
        req.setUserIds(entity.getUser_ids());

        try {
            OapiImChatScenegroupMemberAddResponse rsp = client.execute(req, access_token);
            log.info("场景群新增人员：{}", JSONObject.toJSONString(rsp));

        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 注册互动卡片回调地址
     * @param url  注册的回调地址
     * @param forceUpdate  是否强制注册
     */
    @Override
    public void registerInteractiveCardCallBack(String url, Boolean forceUpdate) {
        String access_token = dingBasicService.getToken("dinggroup");
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/im/chat/scencegroup/interactivecard/callback/register");
        OapiImChatScencegroupInteractivecardCallbackRegisterRequest req = new OapiImChatScencegroupInteractivecardCallbackRegisterRequest();
        //回调地址
        req.setCallbackUrl(url);
        req.setApiSecret(APPSECRET);
        req.setCallbackRouteKey(APPKEY);
        req.setForceUpdate(forceUpdate);
        try {
            OapiImChatScencegroupInteractivecardCallbackRegisterResponse rsp = client.execute(req, access_token);
            System.out.println(rsp.getBody());
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建互动卡片
     * @param entity   互动卡片对象
     */
    @Override
    public String createInteractiveCard(InteractiveCardDTO entity) {
        String accessToken = dingBasicService.getToken("dinggroup");

        log.info("请求创建卡片对象--{}", JSONObject.toJSONString(entity));

        String url="https://api.dingtalk.com/v1.0/im/interactiveCards/send";
        try {
            String ret=httpAPIServiceForDing.doPostDing(url, JSONObject.toJSONString(entity), accessToken);
            log.info("创建互动卡片返回值：{}", ret);
            if (StringUtils.isNotBlank(ret)) {
                JSONObject rsp = JSONObject.parseObject(ret);
                String queryKey=DingUtil.getJsonInsideValue(rsp.getJSONObject("result"), "processQueryKey");
                //推送 业务中台做记录
                InteractiveCardDTO.CardData _param = entity.getCardData();
                InteractiveCardForCPDTO rspDTO = new InteractiveCardForCPDTO();
                rspDTO.setOpenScenegroupId(entity.getOpenConversationId());
                rspDTO.setOpenInteractiveId(entity.getOutTrackId());
                rspDTO.setProcessQueryKey(queryKey);
                rspDTO.setTitle(_param.getCardParamMap().containsKey("new_name")?_param.getCardParamMap().get("new_name"):"未知");
                String oid=cpService.addInteractiveCardToCP(rspDTO);
                if (StringUtils.isBlank(oid)) {
                    log.info("推送cp 存放queryKey失败：{}",queryKey);
                }
                return queryKey;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * 创建 不记录log的互动卡片（定向单聊用）
     * @param entity
     */
    @Override
    public String createInteractiveUncallbackCard(InteractiveCardDTO entity) {
        String accessToken = dingBasicService.getToken("dinggroup");
        String url="https://api.dingtalk.com/v1.0/im/interactiveCards/send";
        try {
            String ret=httpAPIServiceForDing.doPostDing(url, JSONObject.toJSONString(entity), accessToken);
            log.info("创建互动卡片返回值：{}", ret);
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 更新互动卡片
     * @param entity
     * @return
     */
    @Override
    public String updateInteractiveCard(UpdateInteractiveCardDTO entity) {
        String accessToken = dingBasicService.getToken("dinggroup");
        String url="https://api.dingtalk.com/v1.0/im/interactiveCards";
        log.info("请求参数：{}",JSONObject.toJSONString(entity));
        try {
            String ret=httpAPIServiceForDing.doPutDing(url, JSONObject.toJSONString(entity), accessToken);
            log.info("更新 互动卡片返回值：{}", ret);
            if (StringUtils.isNotBlank(ret)) {
                return ret;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * 互动卡片的回调服务-》反馈
     * @param entity
     * @param cardInfo
     */
    @Override
    public void callbackInteractiveCard(JSONObject entity,JSONObject cardInfo) {

        String outTrackId = cardInfo.getString("outTrackId");
        String userId = cardInfo.getString("userId");
        //收到的变更（走私有变量）
        if(entity.containsKey("btn_checkflag")){
            //更新互动卡片
            UpdateInteractiveCardDTO req = new UpdateInteractiveCardDTO();
            UpdateInteractiveCardDTO.CardData paramMap = new UpdateInteractiveCardDTO.CardData();
            Map<String, String> map = new HashMap<>();
            Map<String, Object> privateData = new HashMap<>();
            map.put("checkflag", "true");
            paramMap.setCardParamMap(map);
            privateData.put(userId, paramMap);
            UpdateInteractiveCardDTO.CarOptions carOptions = new UpdateInteractiveCardDTO.CarOptions();
            carOptions.setUpdateCardDataByKey(true);
            carOptions.setUpdatePrivateDataByKey(false);
            req.setCardOptions(carOptions);
            req.setPrivateData(privateData);
            req.setOutTrackId(outTrackId);
            String ret = updateInteractiveCard(req);
            log.info("更新互动卡片请求返回：{}", ret);
        }
    }

    /**
     * 通过群助手 在群内发送消息
     * 如果不需要 自定义模版，可以直接使用钉钉的默认模版 文本类：inner_app_template_text || inner_app_template_markdown
     * @param entity
     */
    @Override
    public void sendMsgByGroupRobot(GroupRobotDTO entity) {
        String accessToken = dingBasicService.getToken("dinggroup");
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/im/chat/scencegroup/message/send_v2");
        OapiImChatScencegroupMessageSendV2Request req = new OapiImChatScencegroupMessageSendV2Request();
        req.setMsgTemplateId(entity.getMsgTemplateId());
        req.setIsAtAll(entity.getIsAtAll());
        req.setMsgParamMap(entity.getMsgParamMap());
        req.setMsgMediaIdParamMap(entity.getMsgMediaIdParamMap());
        req.setTargetOpenConversationId(entity.getTargetOpenConversationId());
        req.setAtMobiles(entity.getAtMobiles());
        req.setAtUsers(entity.getAtUserid());
        req.setReceiverUserIds(entity.getReceiverUserIds());
        req.setReceiverUnionIds(entity.getReceiverUnionIds());
        req.setRobotCode(entity.getRobotCode());
        try {
            OapiImChatScencegroupMessageSendV2Response rsp = client.execute(req, accessToken);
            log.info("机器人发送消息返回：{}", JSONObject.toJSONString(rsp));
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

    /**
     * post方式发送附件到场景群中
     * @param chatId
     * @param media_id
     */
    @Override
    public void sendMsgByPost(String chatId, String media_id) {
        String access_Token = dingBasicService.getToken("dinggroup");
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/chat/send");
        OapiChatSendRequest req = new OapiChatSendRequest();
        req.setChatid(chatId);
        OapiChatSendRequest.Msg msg = new OapiChatSendRequest.Msg();
        OapiChatSendRequest.File file=new OapiChatSendRequest.File();
        file.setMediaId(media_id);
        msg.setFile(file);
        msg.setMsgtype("file");
        req.setMsg(msg);

        try {
            OapiChatSendResponse rsp = client.execute(req, access_Token);
            System.out.println("消息发送rsp："+rsp.getBody());

        } catch (ApiException e) {
            e.printStackTrace();
        }
    }
}
